let storeId = $.cookie("storeId");
let isbn = $.cookie("bookIsbn");
let storeBook = null;
var reg = new RegExp("\"", "g");

function getSaleTemplate(storeBook) {
    return "<div class='row'>" +
        "<div class='col-lg-6'>" +
        "<div class='sp-img_area'>" +
        "<div class='zoompro-border'>" +
        "<img class='zoompro' src='..//..//images//"+ storeBook.img.replace(reg, "") +"' data-zoom-image='..//..//images//"+ storeBook.img +"' alt='' />" +
        "</div>" +
        "</div>" +
        "</div>" +
        "<div class='col-lg-6'>" +
        "<div class='sp-content'>" +
        "<div class='page-navigation'>" +
        "<a href='javascript:void(0)' class='prev'>" +
        "<i class='ion-chevron-left'></i>" +
        "</a>" +
        "<a href='javascript:void(0)' class='next'>" +
        "<i class='ion-chevron-right'></i>" +
        "</a>" +
        "</div>" +
        "<div class='price-box'>" +
        "<span class='new-price'>单价：￥"+ storeBook.price +"</span>" +
        "</div>" +
        "<div class='sp-heading'>" +
        "<h2><a href='javascript:void(0)'>"+ storeBook.bookName +"</a></h2>" +
        "</div>" +
        "<div class='product-desc'>" +
        "<p>"+ storeBook.bookIntroduction +"</p>" +
        "</div>" +
        "<div class='quantity'>" +
        "<label>购买数量</label>" +
        "<div class='cart-plus-minus'>" +
        "<input class='cart-plus-minus-box' value='1' type='text'>" +
        "<div class='dec qtybutton'><i class='fa fa-angle-down'></i></div>" +
        "<div class='inc qtybutton'><i class='fa fa-angle-up'></i></div>" +
        "</div>" +
        "<div class='additional-btn_area'>" +
        "<a class='additional_btn' href='javascript: void(0);'>购买</a>" +
        "</div>" +
        "</div>" +
        "<div class='qty-btn_area'>" +
        "<ul>" +
        "<li><a class='qty-btn' href='javascript: void(0);' data-toggle='tooltip' title='Add To Wishlist'><i class='ion-android-favorite-outline'></i>收藏</a></li>" +
        "<li><a class='qty-btn' href='javascript: void(0);' data-toggle='tooltip' title='Compare This Product'><i class='ion-bag'></i>加入购物车</a></li>" +
        "</ul>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>"
}

function addRelation(relation) {
    let num = 0;
    if (relation == "购物车") {
        num = $("div.cart-plus-minus>input.cart-plus-minus-box").val();
    }
    $.ajax({
        type: "POST",
        url: "/api/userBookRelation/u/addUserBookRelation",
        dataType: "text",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify({
            "bookIsbn": isbn,
            "relation": relation,
            "storeId": storeId,
            "num": num
        }),
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
               alert("成功");
            }else {
               alert(data.msg + ", 请前往购物车或者收藏页面查看");
            }
            updateRecommendBooks();
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    })
    initRelationBook();
}

function getStoreBook() {
    var result = null;
    var formData = new FormData();
    formData.append("isbn", isbn);
    formData.append("storeId", storeId);
    $.ajax({
        type: "post",
        url: "/api/storeBook/v/getStoreBookByStoreAndIsbn",
        async: false,
        dataType: "text",
        data: formData,
        processData: false,
        contentType: false,
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                result = JSON.parse(data.data);
            }else {
                result = null;
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return result;
}

function addBehavior() {
    $.ajax({
        type: "POST",
        url: "/api/userBehavior/u/addBehavior",
        dataType: "text",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify({
            "isbn": isbn,
            "behavior": "PURCHASE"
        }),
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                alert("购买成功");
                updateRecommendBooks();
            }else {
                alert("购买失败");
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    })
}

$(document).ready(function() {
    if (typeof storeId !== "undefined" && typeof isbn !== "undefined") {
        storeBook = getStoreBook();
        $("div.sp-nav>div").append(getSaleTemplate(storeBook));
        $("div.qty-btn_area>ul li").on("click", function (){
            let str = $(this).find("a").text();
            if (str.indexOf("收藏")>=0) {
                addRelation("收藏");
            }else if(str.indexOf("购物车")>=0){
                addRelation("购物车");
            }

        })
        $("a.additional_btn").on("click", function() {
            addBehavior();
        })
        $('.cart-plus-minus').append(
            '<div class="dec qtybutton"><i class="fa fa-angle-down"></i></div><div class="inc qtybutton"><i class="fa fa-angle-up"></i></div>'
        );
        $('.qtybutton').on('click', function() {
            var $button = $(this);
            var oldValue = $button.parent().find('input').val();
            if ($button.hasClass('inc')) {
                var newVal = parseFloat(oldValue) + 1;
            } else {
                // Don't allow decrementing below zero
                if (oldValue > 1) {
                    var newVal = parseFloat(oldValue) - 1;
                } else {
                    newVal = 1;
                }
            }
            $button.parent().find('input').val(newVal);
        });

    }
})
